/*
 * Copyright 2009 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.deepsplink.navigation.command {
	import org.splink.deepsplink.deeplink.IDeeplinkController;
	import org.splink.deepsplink.navigation.INavigation;
	import org.splink.deepsplink.page.params.PageParameterUtil;

	/**
	 * <code>INavigationCommand</code> default implementation
	 * 
	 * @author Max Kugland
	 */
	final public class NavigationCommand implements INavigationCommand {
		private var _deeplinkCtrl : IDeeplinkController;

		public function NavigationCommand(deepLinkCtrl : IDeeplinkController) {
			_deeplinkCtrl = deepLinkCtrl;
		}

		/**
		 * @inheritDoc
		 */
		public function registerNavigation(navigation : INavigation) : void {
			_deeplinkCtrl.registerNavigation(navigation);
		}

		/**
		 * @inheritDoc
		 */
		public function unregisterNavigation(navigation : INavigation) : void {
			_deeplinkCtrl.unregisterNavigation(navigation);
		}

		/**
		 * Executes the gotoPage command. 
		 * 
		 * @param data the id of the page to go to
		 * 
		 * @inheritDoc
		 */
		public function gotoPage(pageId : String, pageParams : Array = null) : void {
			_deeplinkCtrl.gotoPage(pageId, pageParams);
		}
		
		/**
		 * @inheritDoc
		 */
		public function get currentPageId() : String {
			if(_deeplinkCtrl.history.length > 0) {
				return PageParameterUtil.extractId(_deeplinkCtrl.history[_deeplinkCtrl.history.length-1]);
			} else {
				return "";
			}
		}
		
		/**
		 * @inheritDoc
		 */
		public function get currentPageParameters() : Array {
			return PageParameterUtil.extractParams(_deeplinkCtrl.history[_deeplinkCtrl.history.length-1]);
		}

		/**
		 * @inheritDoc
		 */
		public function back() : Boolean {
			if(_deeplinkCtrl.history.length < 2) return false;
			_deeplinkCtrl.history.pop();
			var fullPageId : String = _deeplinkCtrl.history.pop();
			if(fullPageId) {
				var id : String = PageParameterUtil.extractId(fullPageId);				var params : Array = PageParameterUtil.extractParams(fullPageId);
				gotoPage(id, params);
				return true;
			}
			return false;
		}
	}
}
